package learn.ch1.connection;

import java.sql.Connection;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Description todo
 * @Author yusj
 * @Date 2021/12/14
 * @Version 1.0
 */
public class Worker implements Runnable{

    private DbPool pool;
    //获取到链接的数量
    private AtomicInteger got;
    //没获取到链接的数量
    private AtomicInteger notGot;
    private CountDownLatch count;
    private long waitTime;

    public Worker(DbPool pool,AtomicInteger got,AtomicInteger notGot,CountDownLatch count,long waitTime){
        this.pool=pool;
        this.got=got;
        this.notGot=notGot;
        this.count=count;
        this.waitTime=waitTime;
    }

    @Override
    public void run() {
        Connection conn=null;
        try {
            String thname=Thread.currentThread().getName();
            System.out.println(Thread.currentThread().getName()+","+pool);
            conn=pool.getConnection(waitTime);
            System.out.println(thname+","+conn);
            if(conn!=null){
                got.incrementAndGet();
                Thread.sleep(10000);
            }else{
                notGot.incrementAndGet();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            if(conn!=null){
                pool.releaseConn(conn);
            }
        }
        count.countDown();
    }
}
